import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../utils/screen_adapter.dart';

class CustomSearchBar extends StatefulWidget {
  final TextEditingController controller;
  final String hintText;
  final Function(String) onChanged;
  final Function(String) onSubmitted;
  final VoidCallback? onClear;
  final bool showClearButton;
  final bool autofocus;
  final List<String> suggestions;
  final Function(String)? onSuggestionTap;

  const CustomSearchBar({
    Key? key,
    required this.controller,
    this.hintText = '搜索Wiki...',
    required this.onChanged,
    required this.onSubmitted,
    this.onClear,
    this.showClearButton = true,
    this.autofocus = false,
    this.suggestions = const [],
    this.onSuggestionTap,
  }) : super(key: key);

  @override
  State<CustomSearchBar> createState() => _CustomSearchBarState();
}

class _CustomSearchBarState extends State<CustomSearchBar>
    with TickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;
  final FocusNode _focusNode = FocusNode();
  bool _isFocused = false;
  bool _showSuggestions = false;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 200),
      vsync: this,
    );
    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 1.02,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));

    _focusNode.addListener(_onFocusChanged);
    
    if (widget.autofocus) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _focusNode.requestFocus();
      });
    }
  }

  @override
  void dispose() {
    _animationController.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  void _onFocusChanged() {
    setState(() {
      _isFocused = _focusNode.hasFocus;
      _showSuggestions = _isFocused && 
                        widget.suggestions.isNotEmpty && 
                        widget.controller.text.isNotEmpty;
    });

    if (_isFocused) {
      _animationController.forward();
    } else {
      _animationController.reverse();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        _buildSearchField(),
        if (_showSuggestions) _buildSuggestionsList(),
      ],
    );
  }

  // 构建搜索框
  Widget _buildSearchField() {
    return AnimatedBuilder(
      animation: _scaleAnimation,
      builder: (context, child) {
        return Transform.scale(
          scale: _scaleAnimation.value,
          child: Container(
            height: 48.h,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: ScreenAdapter.borderRadius(all: 24),
              border: Border.all(
                color: _isFocused 
                    ? const Color(0xFF4CAF50)
                    : const Color(0xFFE0E0E0),
                width: _isFocused ? 2 : 1,
              ),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(_isFocused ? 0.1 : 0.05),
                  blurRadius: _isFocused ? 8.r : 4.r,
                  offset: Offset(0, _isFocused ? 4.h : 2.h),
                ),
              ],
            ),
            child: Row(
              children: [
                // 搜索图标
                Padding(
                  padding: ScreenAdapter.padding(left: 16, right: 8),
                  child: Icon(
                    Icons.search,
                    size: 20.r,
                    color: _isFocused 
                        ? const Color(0xFF4CAF50)
                        : const Color(0xFF9E9E9E),
                  ),
                ),
                
                // 输入框
                Expanded(
                  child: TextField(
                    controller: widget.controller,
                    focusNode: _focusNode,
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: const Color(0xFF333333),
                    ),
                    decoration: InputDecoration(
                      hintText: widget.hintText,
                      hintStyle: TextStyle(
                        fontSize: 16.sp,
                        color: const Color(0xFF9E9E9E),
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.zero,
                    ),
                    onChanged: (value) {
                      widget.onChanged(value);
                      setState(() {
                        _showSuggestions = _isFocused && 
                                          widget.suggestions.isNotEmpty && 
                                          value.isNotEmpty;
                      });
                    },
                    onSubmitted: widget.onSubmitted,
                    textInputAction: TextInputAction.search,
                  ),
                ),
                
                // 清除按钮
                if (widget.showClearButton && widget.controller.text.isNotEmpty)
                  Padding(
                    padding: ScreenAdapter.padding(right: 8),
                    child: GestureDetector(
                      onTap: () {
                        widget.controller.clear();
                        widget.onChanged('');
                        if (widget.onClear != null) {
                          widget.onClear!();
                        }
                        setState(() {
                          _showSuggestions = false;
                        });
                      },
                      child: Container(
                        width: 24.r,
                        height: 24.r,
                        decoration: BoxDecoration(
                          color: const Color(0xFF9E9E9E),
                          shape: BoxShape.circle,
                        ),
                        child: Icon(
                          Icons.close,
                          size: 16.r,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                
                SizedBox(width: 8.w),
              ],
            ),
          ),
        );
      },
    );
  }

  // 构建建议列表
  Widget _buildSuggestionsList() {
    return Container(
      margin: ScreenAdapter.padding(top: 8),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: ScreenAdapter.borderRadius(all: 12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 8.r,
            offset: Offset(0, 4.h),
          ),
        ],
      ),
      child: Column(
        children: [
          Container(
            padding: ScreenAdapter.padding(horizontal: 16, vertical: 8),
            child: Row(
              children: [
                Icon(
                  Icons.history,
                  size: 16.r,
                  color: const Color(0xFF9E9E9E),
                ),
                SizedBox(width: 8.w),
                Text(
                  '搜索历史',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: const Color(0xFF9E9E9E),
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const Spacer(),
                GestureDetector(
                  onTap: () {
                    // 清除搜索历史的回调
                    setState(() {
                      _showSuggestions = false;
                    });
                  },
                  child: Text(
                    '清除',
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: const Color(0xFF4CAF50),
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ],
            ),
          ),
          Divider(height: 1.h, color: const Color(0xFFE0E0E0)),
          ListView.separated(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: widget.suggestions.length.clamp(0, 5), // 最多显示5个建议
            separatorBuilder: (context, index) => Divider(
              height: 1.h,
              color: const Color(0xFFE0E0E0),
            ),
            itemBuilder: (context, index) {
              final suggestion = widget.suggestions[index];
              return ListTile(
                dense: true,
                leading: Icon(
                  Icons.history,
                  size: 16.r,
                  color: const Color(0xFF9E9E9E),
                ),
                title: Text(
                  suggestion,
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: const Color(0xFF333333),
                  ),
                ),
                trailing: GestureDetector(
                  onTap: () {
                    // 删除单个搜索历史项
                  },
                  child: Icon(
                    Icons.close,
                    size: 16.r,
                    color: const Color(0xFF9E9E9E),
                  ),
                ),
                onTap: () {
                  widget.controller.text = suggestion;
                  widget.onSubmitted(suggestion);
                  if (widget.onSuggestionTap != null) {
                    widget.onSuggestionTap!(suggestion);
                  }
                  setState(() {
                    _showSuggestions = false;
                  });
                  _focusNode.unfocus();
                },
              );
            },
          ),
        ],
      ),
    );
  }
}

